package com.commons.plugins.validation;

import org.apache.commons.beanutils.PropertyUtils;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;

/**
 * 在一个对象内, 校验属性最少有一个不为空.
 * @author songzj
 * @date 16/5/30-17:29
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = AtLeastOneNotNull.AtLeastOneNotNullValidator.class)
public @interface AtLeastOneNotNull {

    String message() default "{com.commons.plugins.validation.AtLeastOneNotNull}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    String[] fieldNames();

    class AtLeastOneNotNullValidator implements ConstraintValidator<AtLeastOneNotNull, Object> {

        private String[] fieldNames;

        @Override
        public void initialize(AtLeastOneNotNull atLeastOneNotNull) {
            this.fieldNames = atLeastOneNotNull.fieldNames();
        }

        @Override
        public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
            if (o == null) {
                return false;
            }

            try {
                for (String fieldName : fieldNames) {
                    return PropertyUtils.getProperty(o, fieldName) != null;
                }
            } catch (Exception e) {
                return false;
            }
            return false;
        }
    }
}
